package com.demo.controller;


import com.demo.common.Result;
import com.demo.service.FileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    FileService service;
    @RequestMapping("/getFileListByParam")
    @ResponseBody
    public Result getFileListByParam(@RequestParam("id")String id, @RequestParam("table")String table){
        return service.getFileListByParam(id,table);
    }
    //    文件上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Result fileUpload(MultipartFile file){
        ApplicationHome h = new ApplicationHome(getClass());
        System.out.println(file.getOriginalFilename());
        File jarF = h.getSource();
        System.out.println(jarF.getParentFile().toString());
        File dir=new File(jarF.getParentFile().toString()+File.separator+"upload");
//        if(!dir.exists()){
//            try {
//                dir.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
        InputStream inputStream=null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long timestamp = System.currentTimeMillis();
        String[] split = file.getOriginalFilename().split("\\.");
        String type=split[split.length-1];
        String name=file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf(type)-1);
        System.out.println("name:  "+name+"  type:  "+type);
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+timestamp+"."+type;
        System.out.println(path);
        File destFile=new File(path);
        try {
            FileUtils.copyInputStreamToFile(inputStream,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Double size=file.getSize()*1.0/1024/1024;
        BigDecimal b   =   new   BigDecimal(size);
        size=b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
        Map param=new HashMap();
        param.put("name",name);
        param.put("type",type);
        param.put("size",size+"M");
        param.put("realName",timestamp);
        service.addFile(param);
        System.out.println(param);

        return Result.ok().msg("上传成功").Data(param);
    }

    @RequestMapping("/deleteFileById")
    @ResponseBody
    public Result deleteFileById(@RequestParam("id")String id){
        service.deleteFileById(id);
        return Result.ok();
    }

    @GetMapping("/download")
    public String downloadFile(@RequestParam("id")String id, HttpServletResponse response) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();

        Map fileMap=service.getFileById(id);
        if(fileMap==null){
            return "文件不存在";
        }
//      真实存在服务器upload文件夹的名称
        String realName=fileMap.get("realName").toString();
//        文件原始名称
        String name=fileMap.get("name").toString();
        String type=fileMap.get("type").toString();
        if (realName != null) {
            //设置文件路径
            String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+realName+"."+type;
            File file = new File(path);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setCharacterEncoding("utf-8");
                try {
                    name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
//                response.setContentType("application/octet-stream");

                // 将文件写入输入流
                FileInputStream fileInputStream = null;
                try {
                    fileInputStream = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                InputStream fis = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[0];
                try {
                    buffer = new byte[fis.available()];
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

// 清空response
                response.reset();
                try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                    response.setContentType("application/octet-stream");
                    response.addHeader("Content-Length", "" + file.length());
                    // 设置文件头：最后一个参数是设置下载文件名
                    response.setHeader("Content-disposition", "attachment;filename="+name+"."+type);
                    outputStream.write(buffer);
                    outputStream.flush();
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作

                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }



}
